<template>
    <el-container class="tl-uppy" v-show="!is_close" @click="noop">
        <el-header class="tl-uppy-header flex justify-between align-center" height="38px">
            <div class="tl-uppy-title">上传文件</div>
            <!--            <div class="tl-uppy-title">正在上传 1 项，共 3 项</div>-->
            <div class="tl-uppy-close" @click="handleClose">
                <i class="bx-icon-quxiao"/>
            </div>
        </el-header>
        <div ref="main"/>
    </el-container>
</template>

<script>
    import $ from 'jquery';
    import bytes from '@bixiao/utils/lib/bytes';

    const Uppy = require('@uppy/core');
    const Chinese = require('@uppy/locales/lib/zh_CN');
    const Dashboard = require('@uppy/dashboard');
    const DragDrop = require('@uppy/drag-drop')
    // const GoogleDrive = require('@uppy/google-drive')
    // const Dropbox = require('@uppy/dropbox')
    // const Instagram = require('@uppy/instagram')
    // const Facebook = require('@uppy/facebook')
    // const OneDrive = require('@uppy/onedrive')
    const Webcam = require('@uppy/webcam')
    const ImageEditor = require('@uppy/image-editor')
    const Tus = require('@uppy/tus')
    const XHRUpload = require('@uppy/xhr-upload')
    export default {
        name: "tl-uppy",
        components: {},
        directives: {},
        data() {
            return {
                is_close: true
            };
        },
        props: {
            meta: {
                type: Object,
                default() {
                    return {
                        catalogId: 'bixiao-oss',
                        pid: 0,
                    }
                }
            },
            autoProceed: {
                type: Boolean,
                default: true
            },
            xhr: {
                type: Object,
                default() {
                    return {}
                }
            },
            btnTrigger: {},
            dragDropTarget: [String, HTMLElement],
            host: String,
            api: {
                type: String,
                default: '/project/attachment/uploadFileCenter'
            },
            note: {
                type: String,
                default: '仅图像和视频，2–3个文件，最大100MB'
            },
            height: {
                type: Number,
                default: 470
            }
        },
        computed: {
            xhrOptions() {
                const xhr = this.xhr
                return {
                    validateStatus: this.validateStatus,
                    getResponseData: this.getResponseData,
                    getResponseError: this.getResponseError,
                    ...xhr
                }
            }
        },
        mounted() {
            this.$nextTick(function () {
                this.createUppy();
            })
        },
        methods: {
            validateStatus(statusCode, responseText, response) {
                try {
                    const data = JSON.parse(responseText);
                    return data.code === 0;
                } catch (error) {
                    return false
                }
            },
            getResponseData(responseText, response) {
                if (response.status === 200) {
                    const result = JSON.parse(responseText);
                    const url = result.code === 0 ? result.data.url : null;
                    return {...result, url};
                } else {
                    return responseText
                }
            },
            getResponseError(responseText, response) {
                if (response.status === 200) {
                    return new Error(JSON.parse(responseText).message)
                } else {
                    return new Error(`网络连接失败，请重新检查网络。。。`)
                }
            },
            createUppy() {
                if (this.uppy) this.close();
                const {config, autoProceed = true, meta} = this
                const {restrictions} = config || {};
                if (restrictions && typeof restrictions.maxFileSize === "string") {
                    restrictions.maxFileSize = bytes(restrictions.maxFileSize)
                }
                const api = `${this.host || ''}${this.api}`
                const uppy = new Uppy({
                    autoProceed,
                    ...config,
                    locale: Chinese,
                    debug: true,
                    restrictions
                })
                const trigger = this.btnTrigger
                const target = this.$refs.main;
                uppy.use(Dashboard, {
                    trigger: trigger,
                    inline: true,
                    target: target,
                    replaceTargetContent: true,
                    showProgressDetails: true,
                    note: this.note,
                    height: this.height,
                    metaFields: [
                        {id: 'name', name: '名字', placeholder: '文件名'},
                        {id: 'description', name: '描述', placeholder: '描述文件的含义'}
                    ],
                    browserBackButtonClose: true,
                })
                // uppy.use(Webcam, {target: Dashboard})
                uppy.use(ImageEditor, {target: Dashboard})
                if (this.dragDropTarget) {
                    uppy.use(DragDrop, {
                        target: this.dragDropTarget,
                        width: '100%',
                        height: '100%',
                    })
                } else {
                    uppy.use(DragDrop, {
                        target: this.$parent.$el,
                        width: '100%',
                        height: '100%',
                    })
                }
                const {headers, formData = true, fieldName = 'file', metaFields} = this.xhrOptions || {}
                if (headers && !headers.token) {
                    headers.token = this.$Login.token
                }
                uppy.use(XHRUpload, {
                    withCredentials: true,
                    endpoint: api,
                    ...this.xhrOptions,
                    headers,
                    formData,
                    fieldName,
                    metaFields
                })
                uppy.setMeta(meta)
                // uppy.on('file-added', (file) => {
                //
                // })
                uppy.on('upload-success', (file) => {
                    this.$emit('upload-success', file)
                })

                uppy.on('complete', result => {
                    console.log('successful files:', result.successful)
                    console.log('failed files:', result.failed)
                    this.$emit('complete', result)
                })
                uppy.on('dashboard:modal-open', () => {
                    console.log('Modal is open')
                    this.is_close = false
                })
                uppy.on('dashboard:modal-closed', () => {
                    console.log('Modal is closed')
                })
                uppy.on('dashboard:file-edit-complete', () => {
                    console.log('file-edit-complete')
                    this.handleClose();
                })
                $(trigger).on('click', async () => {
                    this.is_close = false
                    const dom = $(target)
                    const add = dom.find('.uppy-DashboardContent-addMore');
                    if (add && add.length > 0) {
                        add.click()
                        await new Promise(resolve => setTimeout(() => resolve(), 500));
                    }
                    const input = dom.find('.uppy-Dashboard-browse');
                    input.click();
                })
                this.uppy = uppy;
            },
            close() {
                this.uppy && this.uppy.close()
                this.uppy = null;
                $(this.btnTrigger).off('click')
                $('body').off('click', this.handleClose)
            },
            handleClose() {
                this.is_close = true;
                const target = this.$refs.main;
                $(target).find('.uppy-DashboardContent-addMore').click();
            }
        },
        beforeDestroy() {
            this.close();
        }
    };
</script>
<style lang="less" scoped>
    @import '~@uppy/core/dist/style.css';
    @import '~@uppy/dashboard/dist/style.css';
    @import '~@uppy/image-editor/dist/style.css';
    @import '~@uppy/drag-drop/dist/style.css';

    .tl-uppy {
        ::v-deep {
            .uppy-Dashboard-poweredBy {
                display: none;
            }

            .uppy-Dashboard-innerWrap, .uppy-Dashboard-AddFilesPanel {
                border-radius: 0;
                border: none;
            }

            .uppy-Dashboard-inner {
                border: none;
            }
        }

        position: fixed;
        z-index: 51;
        right: 24px;
        bottom: 24px;
        width: 512px;
        border-radius: 12px;
        border: .5px solid #e5e5e5;
        overflow: hidden;
        background: #f5f5f5;
        box-shadow: 0 0 14px rgba(0, 0, 0, .15);

        .tl-uppy-header {
            background: #f5f5f5;
            padding-left: 14px;
            padding-right: 14px;
            border: 0;
            border-bottom: .5px solid #e5e5e5;
        }
    }
</style>
